package com.maxima.attendance.reports;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class ExportReports extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
	private SimpleDateFormat monthYearFormat = new SimpleDateFormat("MMM yyyy");

	public ExportReports() {
		super();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String date = request.getParameter("date");
		if (date != null) {
			Date selectedDate = null;
			try {
				selectedDate = sdf.parse(date);
			}
			catch (ParseException e) {
				e.printStackTrace();
			}
			List<File> files = new Report().getReportFiles(selectedDate);
			export(response, files, monthYearFormat.format(selectedDate));
		}
	}

	public void export(HttpServletResponse response, List<File> files, String filename) throws IOException {
		File tmpDir = getNewTmpDir();
		File zipFile = new File(tmpDir, UUID.randomUUID().toString());
		ZipUtils.createZip(files, zipFile);
		try {
			writeFileToOutput(response, filename, zipFile);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		files.add(zipFile);
		cleanUp(tmpDir, files);
	}

	private File getNewTmpDir() {
		File tmpDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
		tmpDir.mkdir();
		return tmpDir;
	}

	private void cleanUp(File folder, List<File> files) {
		for (File file : files) {
			file.delete();
		}
		if (folder != null) {
			folder.delete();
		}
	}

	private void writeFileToOutput(HttpServletResponse response, String filename, File zipFile) throws Exception {
		response.setContentLength((int) zipFile.length());
		response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".zip\"");
		InputStream inStream = null;
		OutputStream outStream = null;
		try {
			inStream = new FileInputStream(zipFile);
			outStream = response.getOutputStream();
			IOUtils.copy(inStream, outStream);
		}
		catch (Exception e) {
			System.out.println("Error");
			throw e;
		}
		finally {
			try {
				if (inStream != null)
					inStream.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (outStream != null) {
					outStream.flush();
					outStream.close();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
